#!/usr/bin/env python3
"""
依赖包安装脚本
自动安装股票分析系统所需的所有依赖包
"""

import subprocess
import sys
import importlib

def check_package(package_name):
    """检查包是否已安装"""
    try:
        importlib.import_module(package_name)
        return True
    except ImportError:
        return False

def install_package(package_name):
    """安装包"""
    try:
        print(f"正在安装 {package_name}...")
        subprocess.check_call([sys.executable, "-m", "pip", "install", package_name])
        print(f"✅ {package_name} 安装成功")
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ {package_name} 安装失败: {e}")
        return False

def main():
    """主安装函数"""
    print("🚀 股票分析系统依赖包安装")
    print("=" * 50)
    
    # 必需的包列表
    required_packages = [
        ("pandas", "pandas"),
        ("numpy", "numpy"),
        ("yfinance", "yfinance"),
        ("akshare", "akshare"),
        ("tushare", "tushare"),
        ("talib", "talib-binary"),  # 使用预编译版本
    ]
    
    # 可选的包
    optional_packages = [
        ("matplotlib", "matplotlib"),
        ("seaborn", "seaborn"),
        ("plotly", "plotly"),
    ]
    
    print("检查必需依赖包...")
    missing_required = []
    
    for import_name, install_name in required_packages:
        if check_package(import_name):
            print(f"✅ {import_name} 已安装")
        else:
            print(f"❌ {import_name} 未安装")
            missing_required.append((import_name, install_name))
    
    if missing_required:
        print(f"\n需要安装 {len(missing_required)} 个必需包:")
        for import_name, install_name in missing_required:
            print(f"  - {import_name}")
        
        response = input("\n是否现在安装？(y/n): ").lower().strip()
        if response in ['y', 'yes', '是']:
            print("\n开始安装必需包...")
            failed_packages = []
            
            for import_name, install_name in missing_required:
                if not install_package(install_name):
                    failed_packages.append(import_name)
            
            if failed_packages:
                print(f"\n❌ 以下包安装失败: {failed_packages}")
                print("\n手动安装建议:")
                for pkg in failed_packages:
                    if pkg == "talib":
                        print("  TA-Lib安装:")
                        print("    方法1: conda install -c conda-forge ta-lib")
                        print("    方法2: pip install TA-Lib")
                        print("    方法3: 下载预编译wheel文件")
                    else:
                        print(f"    pip install {pkg}")
            else:
                print("\n🎉 所有必需包安装成功！")
        else:
            print("跳过安装")
    else:
        print("\n✅ 所有必需包已安装")
    
    # 检查可选包
    print(f"\n检查可选依赖包...")
    missing_optional = []
    
    for import_name, install_name in optional_packages:
        if check_package(import_name):
            print(f"✅ {import_name} 已安装")
        else:
            print(f"⚠️  {import_name} 未安装 (可选)")
            missing_optional.append((import_name, install_name))
    
    if missing_optional:
        print(f"\n可选包 (用于数据可视化):")
        for import_name, install_name in missing_optional:
            print(f"  - {import_name}")
        
        response = input("\n是否安装可选包？(y/n): ").lower().strip()
        if response in ['y', 'yes', '是']:
            print("\n安装可选包...")
            for import_name, install_name in missing_optional:
                install_package(install_name)
    
    # 最终检查
    print("\n" + "=" * 50)
    print("📋 最终检查")
    print("=" * 50)
    
    all_good = True
    for import_name, _ in required_packages:
        if check_package(import_name):
            print(f"✅ {import_name}")
        else:
            print(f"❌ {import_name}")
            all_good = False
    
    if all_good:
        print("\n🎉 所有必需依赖已就绪！")
        print("\n接下来可以运行:")
        print("  python test_system.py          # 测试系统")
        print("  python stock_analyzer.py AAPL 日线  # 分析股票")
        print("  python example_usage.py demo   # 运行演示")
    else:
        print("\n⚠️  仍有依赖包未安装，请手动安装后再试")
    
    print("=" * 50)

if __name__ == "__main__":
    main()
